<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
    <meta charset="UTF-8">
    <title>购物车</title>
    <link rel="stylesheet" href="./css/style.min.css">
</head>
<script type="text/javascript">
    window.onload=function () {
            document.addEventListener('touchstart',function (event) {
                if(event.touches.length>1){
                    event.preventDefault();
                }
            })
            var lastTouchEnd=0;
            document.addEventListener('touchend',function (event) {
                var now=(new Date()).getTime();
                if(now-lastTouchEnd<=300){
                    event.preventDefault();
                }
                lastTouchEnd=now;
            },false)
        }
</script>
<body>
    <div id="cart-pg" class="cart-pg cl">
        <header class="cl" v-show="header.show">
            <div class="nav-bar cl">
                <span class="goback arrow_l" @click="goback"></span>
                <span class="page-name" v-cloak>{{shop_name}}会员店</span>
            </div>
        </header>
        <div class="main cl">
            <store-order ref="order" v-on:subact="sumtotal"></store-order>
        </div>
        <div class="btm-bar">
            <div class="shopping">
                <a :href="goshopping">
                    <h3>继续</h3>
                    <h3>购物</h3>
                </a>
            </div>
            <div class="check"><a href="#" @click.prevent="gocheckout">去结算<span class="total-counts">({{cart_counts}})</span></a></div>
            <div class="total-accout">
                <h4>合计：<span class="amount" v-cloak>￥{{total.toFixed(2)}}</span></h4>
            </div>
        </div>
        <toast ref="toast"></toast>
        <div class="loading" v-show="loading"></div>
    </div>
    <script type="text/template" id="store-order">
    <div>
        <table v-show="carts_flag" v-cloak>
            <colgroup>
                <col width="36px">
                <col width="90px">
                <col>
            </colgroup>
            <thead>
                <tr>
                    <th colspan="3">
                        <span class="chkbx" :class="{chkbx_n:storechk}" @click="chkallfn"><input type="checkbox" v-model="storechk"  ></span>
                        <span>{{complist['shop']['shopName']}}</span>
                        </th>
                </tr>
            </thead>
            <tbody>
                <tr is="singlecart" ref="singlecart" v-for="(goods,idx) in complist['carts']" :ikey="goods.id" :cart_goods="goods" v-on:chk_act="get_chk" v-on:spin_act="get_spin"   :key="goods.id" v-on:cpu_total="cpued_total">
                    
                </tr>
            </tbody>
        </table>
        <span v-show="!carts_flag" class="loadmore">购物车为空，请先选购一些商品吧！</span>
        </div>
    </script>
    <script type="text/template" id="cart">
                <tr v-cloak>
                    <td>
                        <span class="chkbx" :class="{chkbx_n:chkboxs}"  @click="chkfn" v-show="cart_goods.sku&&cart_goods.sku.validateStatus==1"><input type="checkbox" v-model="chkboxs" ></span>
                    </td>
                    <td>
                        <div class="img-wrap">
                            <div class="soff-shelf" v-if="!cart_goods.sku || cart_goods.sku.validateStatus != 1">已下架</div>
                            <img :src="cart_goods.sku&&cart_goods.sku.small_img?cart_goods.sku.small_img:''" @click="goodsdetail(cart_goods.goodsId)">
                        </div>
                    </td>
                    <td>
                        <a href="#" @click.prevent="goodsdetail(cart_goods.goodsId)" class="order-title"  v-cloak>{{cart_goods.sku?cart_goods.sku.goods_name:""}}</a>
                        <div><span class="attrs" v-cloak @click.prevent="goodsdetail(cart_goods.goodsId)">{{cart_goods.sku?cart_goods.sku.attr_name:""}}</span></div>
                        <div class="price-wrap cl"><span class="price" v-cloak><em>￥</em>{{cart_goods.price}}</span>
                        <div class="goods-spinner cl">
                            <button type="button" class="first" @click="cut">-</button>
                            <input type="text" :value="cart_goods.qty" v-model="sku_num" @blur="countsblur">
                            <button type="button" class="last" @click="add">+</button>
                        </div>
                        <span class="del-ico del" @click="delfn(i)"></span></div>
                    </td>
                </tr>
        </script> 
    <script src="./js/lib/vue.js"></script>
    <script src="./js/min/config.min.js"></script>
    <script src="http://static.jdhui.com/lib/vue-resource/1.2/vue-resource.js"></script>
    <script type="text/javascript" src="./js/min/common.min.js"></script>
    <script src="./js/min/component.min.js"></script>
    <script>
        var store_id = APP.getQueryString("storeid");
        var _stock = APP.getQueryString("stocknum");
        var toast = new component.popup.toast();
        var order = Vue.component("store-order", {
            template: "#store-order",
            data: function() {
                return {
                    complist: {
                        shop: {
                            shopName: ''
                        },
                        carts: [{
                            sku: {
                                goods_name: ""
                            }
                        }]
                    },
                    subtotal: 0,
                    gap: 0,
                    storechk: true,
                    chkboxs: [],
                    cartids: [],
                    cartnums: 0,
                    carts_flag: false //判断购物车是否为空
                }
            },
            mounted: function() {
                Vue.http.options.xhr = {
                    withCredentials: true
                }
                Vue.http.options.credentials = true;
                var that = this;
                Vue.http.post(APIJAVA + 'c/mobile/cart/list?shopId=' + store_id, {

                }, {
                    emulateJSON: true
                }).then(function(_res) {
                    if (_res.body.code == 0) {
                        cart.$refs.toast.show(_res.body.message)
                        that.carts_flag = false;
                    }else if(_res.body.code == -100) {
                        cart.$refs.toast.show(_res.body.message);
                        setTimeout(function () {
                            window.location.href="login.html?storeid="+store_id;
                        },2000)
                    }else {
                        that.carts_flag = true;
                        that.complist = _res.body.obj&&_res.body.obj[0];
                        for (var i = 0; i < that.complist['carts'].length; i++) {
                            if (that.complist['carts'][i]['sku'] && that.complist['carts'][i]['sku']['validateStatus'] && that.complist['carts'][i]['sku']['validateStatus'] == 1) {
                                that.cartids.push(that.complist['carts'][i]['id']);
                                that.cartnums += parseInt(that.complist['carts'][i]['qty']);
                                that.subtotal += that.complist['carts'][i]['price'] * that.complist['carts'][i]['qty']
                            }
                            // console.log(that.complist['carts'][i]['qty'])
                        }
                        that.$emit('subact', that.subtotal, that.cartids, that.cartnums);
                    }
                    cart.loading=false;
                })
            },
            methods: {
                chkallfn: function() {
                    this.storechk = !this.storechk;
                    for (var i = 0; i < this.$refs.singlecart.length; i++) {
                        if (this.complist['carts'][i]['sku'] && this.complist['carts'][i]['sku']['validateStatus'] == 1) {
                            this.$refs.singlecart[i].chkboxs = this.storechk;
                        }
                    }
                    var _list = this.complist['carts'];
                    var _storechk = this.storechk;
                    this.cartids = [];
                    for (var i = 0; i < _list.length; i++) {
                        if (_storechk && this.complist['carts'][i]['sku'] && this.complist['carts'][i]['sku']['validateStatus'] == 1) {
                            this.cartids.push(this.complist['carts'][i]['id'])
                        }
                    }
                    if (_storechk == false) { //选中时点击
                        this.subtotal = 0;
                        this.cartnums=0;
                    } else { //未选中时点击
                        this.cpued_total();
                       /* this.subtotal = 0;
                        for (var i = 0; i < this.$refs.singlecart.length; i++) {
                            if (this.$refs.singlecart[i]['chkboxs']) {
                                this.subtotal += this.$refs.singlecart[i]['cart_price']
                            }
                        }*/
                    }
                    this.$emit('subact', this.subtotal, this.cartids, this.cartnums);
                },
                get_chk: function(m, n) {
                    if (m > 0) {
                        this.cartids.push(n)
                    } else {
                        this.cartids.remove(n)
                    }
                    this.$emit('subact', this.subtotal, this.cartids, this.cartnums);
                },
                get_spin: function(m) {
                    this.$emit('subact', this.subtotal, this.cartids, this.cartnums);
                },
                cpued_total: function() {
                    this.subtotal = 0;
                    this.cartnums = 0;
                    for (var i = 0; i < this.$refs.singlecart.length; i++) {
                        if (this.$refs.singlecart[i]['chkboxs']) {
                            this.subtotal += this.$refs.singlecart[i]['cart_price']
                            this.cartnums += parseInt(this.$refs.singlecart[i]['sku_num'])
                        }
                    }
                    this.$emit('subact', this.subtotal, this.cartids, this.cartnums);
                }
            },
            computed: {
            }
        });

        Vue.component("singlecart", {
            template: "#cart",
            props: ["cart_goods", "ikey"],
            data: function() {
                return {
                    sku_num: this.cart_goods.qty,
                    cart_price: this.cart_goods.price * this.cart_goods.qty,
                    chkboxs: true,
                    goods: "",
                    cartids: "",
                    i: this.ikey

                }
            },
            methods: {
                cut: function() {
                    if (this.sku_num > 1) {
                        this.sku_num--;
                        this.cart_price = this.cart_price - this.cart_goods['price'];
                        var _gap = 0 - this.cart_goods['price'];
                        if (this.chkboxs) {
                            this.$emit("spin_act", _gap)
                            this.$emit("cpu_total");
                        }
                        this.change_cartnum(this.cart_goods['id'], this.sku_num)
                    } else {
                        cart.$refs.toast.show("数量不能小于1");
                    }
                },
                add: function() {
                    if (this.sku_num < 9999) {
                        this.sku_num++;
                        this.cart_price = this.cart_price + this.cart_goods['price'];
                        var _gap = this.cart_goods['price'];
                        if (this.chkboxs) {
                            this.$emit("spin_act", _gap)
                            this.$emit("cpu_total");
                        }
                        this.change_cartnum(this.cart_goods['id'], this.sku_num)
                    } else {
                        cart.$refs.toast.show("数量不能大于9999");
                    }

                },
                countsblur: function() {
                    var reg_counts = /^[1-9]\d*|0$/;
                    if (this.sku_num < 1 || this.sku_num > 9999 || !reg_counts.test(this.sku_num)) {
                        cart.$refs.toast.show("请输入有效数量");
                        this.sku_num = 1;
                    }
                    this.cart_price = this.cart_goods['price'] * this.sku_num
                    this.change_cartnum(this.cart_goods['id'], this.sku_num)
                    this.$emit("cpu_total");
                },
                chkfn: function(m) {
                    this.chkboxs = !this.chkboxs;
                    var chkcounts = 0;
                    var _singlecart = cart.$refs.order.$refs.singlecart;
                    var _gap = this.cart_goods['price'] * this.sku_num;
                    if (this.chkboxs) {
                        this.gap = _gap;
                        this.cartids = this.cart_goods['id']
                    } else {
                        this.gap = 0 - _gap;
                        this.cartids = this.cart_goods['id']
                    }
                    this.$emit('chk_act', this.gap, this.cartids);
                    this.$emit("cpu_total");

                    for (var i = 0; i < _singlecart.length; i++) {
                        if (_singlecart[i]['chkboxs'] == true) {
                            chkcounts++;
                        }
                    }
                    if (chkcounts < _singlecart.length || _singlecart.length == 0) {
                        cart.$refs.order.storechk = false;
                    } else {
                        cart.$refs.order.storechk = true;
                    }
                },

                delfn: function(index) {
                    this.cart_price = 0;
                    this.sku_num = 0;
                    this.$emit("cpu_total");
                    for (var j = 0; j < cart.$refs.order.complist["carts"].length; j++) {
                        if (cart.$refs.order.complist["carts"][j]['id']==index) {
                            cart.$refs.order.complist["carts"].splice(j, 1);
                        }
                    }
                    var chkcounts = 0;
                    var _singlecart = cart.$refs.order.$refs.singlecart;
                    if (this.chkboxs) {
                        this.cartids = this.cart_goods['id'];
                        this.$emit('chk_act', -1, this.cartids); //传入-1以删除掉购物车id
                        this.$emit("cpu_total");
                    }
                    for (var i = 0; i < _singlecart.length; i++) {
                        if (_singlecart[i]['chkboxs'] == true) {
                            chkcounts++;
                        }
                    }
                    
                    if (chkcounts < cart.$refs.order.complist["carts"].length || cart.$refs.order.complist["carts"].length == 0) {
                        
                        cart.$refs.order.storechk = false;
                    } else {
                        cart.$refs.order.storechk = true;
                    }

                    if (cart.$refs.order.complist["carts"].length == 0) {
                        cart.$refs.order.carts_flag = false;
                        cart.$refs.toast.show('购物车为空,请先选购一些商品吧')
                    }
                    Vue.http.get(APIJAVA + '/c/mobile/cart/del?id=' + this.cart_goods.id + '&shopId=' + store_id, function(_res) {
                        cart.$refs.toast.show(_res.body.message);
                    })
                },
                change_cartnum: function(c_id, c_num, _url) {
                    Vue.http.post(APIJAVA + '/c/mobile/cart/modify?&shopId=' + store_id, {
                        "id": c_id, // 购物车ID
                        "goodsId": "", // 商品ID
                        "qty": c_num, // 数量（减数量填负数；加数量填正数）
                        "shopId": store_id, // 店铺ID
                        "addType": 1 // 1 覆盖原数量，非 1 累加数量
                    }, {
                        emulateJSON: true
                    }).then(function(_res) {
                        if (_url) {
                            window.location.href = _url;
                        }
                    })
                },
                goodsdetail: function(m) {
                    Vue.http.get(APIPHP + 'index.php?r=goods/index/check&storeid=' + store_id + '&id=' + m, {
                        emulateJSON: true
                    }).then(function(_res) {
                        if (_res.body.error_code == 0) {
                            window.location.href = 'goods-detail.html?storeid=' + store_id + '&id=' + m;
                        } else {
                            cart.$refs.toast.show('该商品已下架');
                        }
                    }.bind(this));
                }
            },
            mounted: function() {
                this.chkboxs = this.valid_flag;
            },
            computed: {
                cpued_price: function() {
                    return this.cart_goods['price'] * this.sku_num;
                },
                valid_flag: function() {
                    if (this.cart_goods.sku && this.cart_goods.sku.validateStatus == 1) {
                        return true;
                    }

                }
            }
        })
        var cart = new Vue({
            el: "#cart-pg",
            data: {
                header: {
                    show: !APP.iswechat()
                },
                storeorder: '',
                total: 0,
                cartids: '',
                shop_name: '',
                cart_counts: 0,
                loading:true
            },
            mounted: function() {
                APP.init(this, function() {
                    this.shop_name = APP.getCookie('shopname');
                }.bind(this), function(arg) {
                    this.shop_name = arg.body.data.shop.shop_name;
                }.bind(this));
            },
            component: {
                'toast': toast
            },
            methods: {
                goback: function() {
                    window.history.go(-1);
                },
                gocheckout: function() {
                    if (this.cartids == "") {
                        this.$refs.toast.show('请选择购物车商品');
                        return false;
                    } else {
                        window.location.href = 'checkout.html?storeid=' + store_id + '&cartIds=' + this.cartids
                    }
                },
                sumtotal: function(m, n, num) {
                    this.total = m;
                    this.cart_counts = parseInt(num);
                    if (n) {
                        this.cartids = n.join(",")
                            // this.cart_counts=n.length;
                    } else {
                        this.cartids = "";
                    }
                }
            },
            computed: {
                goshopping: function() {
                    return 'goods-list.html?storeid=' + store_id;
                }
            }
        })
    </script>
</body>

</html>